<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="客户名称">
              <a-input placeholder="请输入客户名称" v-model="queryParam.departName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="创建类型">
              <j-dict-select-tag placeholder="请选择创建类型" v-model="queryParam.createType" dictCode="merchant_create_type"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="创建时间">
              <a-range-picker v-model="queryParam.effectTime" show-time style="width: 100%" valueFormat="YYYY-MM-DD HH:mm:ss" @change="effectTimeChange" />
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="客户分组">
                <j-dict-select-tag type="list" v-model="queryParam.groupId" dictCode="hz_sys_merchant_group,name,id,system" placeholder="请选择客户分组" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button> -->
      <!-- <a-button type="primary" icon="download" @click="handleExportXls('客户机构表')">导出</a-button> -->
      <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload> -->
      <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query> -->
      <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown> -->
      <a-button v-has="'sysDepart:add'" @click="handleAdd" type="primary" icon="plus">创建客户</a-button>
      <a-button type="primary" @click="handleBatchGroup" v-has="'sysDepart:group'">批量分组设置</a-button>
      <a-button type="primary" @click="handleBatchAdd" v-has="'sysDepart:edit'">批量添加产品</a-button>
      <a-button type="primary" @click="handleCreateGroup" v-has="'sysDepart:group'">创建分组</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        :customRow="selectRowData">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;" :preview="0"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <template slot="nameSlot" slot-scope="text, record">
          <j-ellipsis :value="text" :length="20"></j-ellipsis>
        </template>

        <template slot="merStatusSlot" slot-scope="text, record">
          <span :style="{color: text === '1' ? '#67c23a' : 'red'}">{{ record.status_dictText }}</span>
        </template>

        <span slot="action" slot-scope="text, record">
          <a v-if="record.status === '0'" v-has="'sysDepart:frozen'" @click="handleEnable(record)">启用</a>
          <a style="color: red;" v-if="record.status === '1'" v-has="'sysDepart:frozen'" @click="handleEnable(record)">冻结</a>

          <a-divider type="vertical" v-if="record.status === '0' || record.status === '1'" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <!-- <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item> -->
              <a-menu-item v-has="'sysDepart:changePd'">
                <a @click="handleChangePassword(record)">修改密码</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleCopy(record)">复制账号信息</a>
              </a-menu-item>
              <a-menu-item v-has="'sysDepart:edit'">
                <a @click="handleEdit_(record, '编辑客户')" >编辑客户</a>
              </a-menu-item>
              <a-menu-item v-has="'sysDepart:edit'">
                <a @click="handleEditProduct(record)">编辑物流产品</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleCostCenter(record)">编辑成本中心</a>
              </a-menu-item>
              <!-- 操作日志 -->
              <a-menu-item>
                <j-operate-log :id="record.id"></j-operate-log>
              </a-menu-item>
              <!-- <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item> -->
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>

    <sys-merchant-org-modal ref="modalForm" @ok="modalFormOk" :rolesOptions="rolesOptions"></sys-merchant-org-modal>
    <!-- 批量分组设置 -->
    <sys-batch-group-modal ref="modalGroupForm" @ok="modalFormOk"></sys-batch-group-modal>
    <!-- 批量添加产品 -->
    <sys-batch-add-modal ref="modalAddForm" @ok="modalFormOk"></sys-batch-add-modal>
    <!-- 创建分组 -->
    <sys-create-group-modal ref="modalCreateForm" @ok="modalFormOk"></sys-create-group-modal>
    <!-- 编辑物流产品 -->
    <sys-edit-product-modal ref="modaleditForm" @ok="modalFormOk"></sys-edit-product-modal>
    <!-- 编辑成本中心 -->
    <sys-cost-center-modal ref="modalCostCenterForm" @ok="modalFormOk"></sys-cost-center-modal>
    <!-- 修改密码 -->
    <sys-change-password-modal ref="modalChangeForm" @ok="modalFormOk"></sys-change-password-modal>
  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import SysMerchantOrgModal from './modules/SysMerchantOrgModal.vue'
import SysBatchGroupModal from './modules/SysBatchGroupModal.vue'
import SysBatchAddModal from './modules/SysBatchAddModal.vue'
import SysCreateGroupModal from './modules/SysCreateGroupModal.vue'
import SysEditProductModal from './modules/SysEditProductModal.vue'
import SysChangePasswordModal from './modules/SysChangePasswordModal.vue'
import SysCostCenterModal from './modules/SysCostCenterModal.vue'
// import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
import { getAction } from '@/api/manage'
import { queryall } from '@/api/api'

export default {
  name: 'SysMerchantOrgList',
  mixins:[JeecgListMixin, mixinDevice],
  components: {
    SysMerchantOrgModal,
    SysBatchGroupModal,
    SysBatchAddModal,
    SysCreateGroupModal,
    SysEditProductModal,
    SysChangePasswordModal,
    SysCostCenterModal
  },
  data () {
    return {
      description: '客户机构表管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'客户名称',
          align:"center",
          dataIndex: 'departName',
          scopedSlots: { customRender: 'nameSlot' }
        },
        {
          title:'客户分组',
          align:"center",
          dataIndex: 'groupId_dictText'
        },
        {
          title:'客户ID',
          align:"center",
          dataIndex: 'orgCode'
        },
        {
          title:'手机号码',
          align:"center",
          dataIndex: 'mobile'
        },
        {
          title:'客户状态',
          align:"center",
          dataIndex: 'status',
          scopedSlots: { customRender: 'merStatusSlot' }
        },
        {
          title:'创建类型',
          align:"center",
          dataIndex: 'createType_dictText'
        },
        {
          title:'客户级别',
          align:"center",
          dataIndex: 'departLevel_dictText'
        },
        {
          title:'客户类型',
          align:"center",
          dataIndex: 'merchantType_dictText'
        },
        {
          title:'组织权限',
          align:"center",
          dataIndex: 'maxPermRoleId_dictText'
        },
        {
          title:'创建时间',
          align:"center",
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed:"right",
          width:147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: "/sys/sysDepart/list",
        delete: "/sys/sysDepart/delete",
        deleteBatch: "/sys/sysDepart/deleteBatch",
        exportXlsUrl: "/sys/sysDepart/exportXls",
        importExcelUrl: "sys/sysDepart/importExcel",
        queryAllByOrgCode: '/hzkj-system/sys/costCenter/queryAllByOrgCode',
      },
      // superFieldList:[],
      rolesOptions: []
    }
  },
  created() {
    // this.getSuperFieldList();
    this.initRoleList();
  },
  computed: {
    importExcelUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
  },
  methods: {
    initDictConfig(){
    },
    selectRowData(record,index){
      const that = this
      return {
        on:{
          dblclick:() => {
            // this.handleDetail(record)
          }
        }
      }
    },
    // getSuperFieldList(){
    //   let fieldList=[];
    //   fieldList.push({type:'datetime',value:'createTime',text:'创建日期'})
    //   fieldList.push({type:'string',value:'name',text:'客户名称',dictCode:''})
    //   fieldList.push({type:'string',value:'merNo',text:'客户编号',dictCode:''})
    //   fieldList.push({type:'string',value:'phone',text:'手机号码',dictCode:''})
    //   fieldList.push({type:'string',value:'merStatus',text:'客户状态',dictCode:'is_enable'})
    //   fieldList.push({type:'string',value:'createType',text:'创建类型',dictCode:'merchat_create_type'})
    //   fieldList.push({type:'string',value:'merLevel',text:'客户级别',dictCode:'merchat_level'})
    //   fieldList.push({type:'string',value:'groupId',text:'客户分组',dictCode:'hz_sys_merchant_group,name,id'})
    //   this.superFieldList = fieldList
    // },
    effectTimeChange(){
      this.queryParam.createTime_begin = this.queryParam.effectTime && this.queryParam.effectTime[0];
      this.queryParam.createTime_end = this.queryParam.effectTime && this.queryParam.effectTime[1];
    },
    handleBatchGroup(){
      if(!(this.selectedRowKeys && this.selectedRowKeys.length)){
        this.$message.warning('请选择数据');
        return;
      }
      this.$refs.modalGroupForm.add();
      this.$refs.modalGroupForm.title = '批量分组设置';
      this.$refs.modalGroupForm.disableSubmit = false;
      this.$refs.modalGroupForm.selectedRowKeys = this.selectedRowKeys;
    },
    handleBatchAdd(){
      if(!(this.selectedRowKeys && this.selectedRowKeys.length)){
        this.$message.warning('请选择数据');
        return;
      }
      this.$refs.modalAddForm.add();
      this.$refs.modalAddForm.title = '批量添加产品';
      this.$refs.modalAddForm.disableSubmit = false;
      this.$refs.modalAddForm.selectedRowKeys = this.selectedRowKeys;
    },
    handleCreateGroup(){
      this.$refs.modalCreateForm.add();
      this.$refs.modalCreateForm.title = '创建分组';
      this.$refs.modalCreateForm.disableSubmit = false;
    },
    handleChangePassword(record){
      this.$refs.modalChangeForm.edit(record);
      this.$refs.modalChangeForm.title = '修改密码';
      this.$refs.modalChangeForm.disableSubmit = false;
    },
    handleEditProduct(record){
      this.$refs.modaleditForm.edit(record);
      this.$refs.modaleditForm.title = '编辑物流产品';
      this.$refs.modaleditForm.disableSubmit = false;
    },
    handleEdit_(record, title){
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = title;
      this.$refs.modalForm.disableSubmit = false;
    },
    //编辑成本中心
    handleCostCenter(record){
      const that = this
      //获取已绑定的成本中心
      getAction(that.url.queryAllByOrgCode, { orgCode:record.orgCode }).then((res) => {
        if (res.success) {
          const targetKeys = res.result.map(item=>item.settlementOrgId) || []
          that.$refs.modalCostCenterForm.edit(record,targetKeys);
        } else {
          this.$message.warning(res.message)
        }
      })
      // that.$refs.modalCostCenterForm.edit(record,'edit')
    },
    handleCopy(record){
      const textarea = document.createElement('textarea');
      textarea.value = `【系统登陆信息】\n  客户名称：${record.departName || ''}\n  账号名：${record.mobile || ''}\n  系统网址：${window.location.origin || ''}`;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand("copy");
      document.body.removeChild(textarea);
      this.$message.success('已复制客户主账号信息至粘贴板');
    },
    handleEnable(record){
      const that = this
      if(record.status === '1'){
        that.$confirm({
          title:'客户冻结',
          content: (
            <div>
              <div style="color: red">冻结后下属账号均不可用</div>
              <div>你还要继续吗？</div>
            </div>
          ),
          okText: '继 续',
          onOk() {
            that.handlePost(record);
          },
          onCancel() {  },
        });
      }else{
         //获取已绑定的成本中心
       getAction(that.url.queryAllByOrgCode, { orgCode:record.orgCode }).then((res) => {
        if (res.success) {
          const targetKeys = res.result.map(item=>item.settlementOrgId) || []
          if(targetKeys.length < 1 && record.status === '0'){
            this.$confirm({
            title:'该客户无成本中心',
            content:h=><div><div style="color:#F04134;">无成本中心客户鸿展账号无法启用</div><div style="color:#8A8585a5;">请配置成本中心</div></div>,
            okText:'去配置',
            onOk() {
              that.$refs.modalCostCenterForm.edit(record,targetKeys);
            }, 
           })
          }else{
            that.handlePost(record);
          }
        } else {
          this.$message.warning(res.message)
        }
      })
      }
    },
    handlePost(record){
      let parmas = {
        isEnable: record.status === '0' ? '1' : '0'
      }
      getAction('/sys/sysDepart/changeEnable/'+record.id, parmas).then((res)=>{
        if(res.success){
          this.$message.success(res.message)
          this.loadData();
        }else{
          this.$message.warning(res.message)
        }
      })
    },
    //初始化角色字典
    initRoleList() {
      queryall().then((res) => {
        if (res.success) {
          this.rolesOptions = res.result.map(item => {
            return {
              text : item.roleName,
              value: item.id
            }
          })
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>